package com.sd365.permission.centre.service.impl;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author yangshaoqi
 * @Date 2020/12/14 21:29
 * @Version 1.0
 **/

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.sd365.common.core.annotation.mybatis.Pagination;
import com.sd365.common.core.annotation.stuffer.CommonFieldStuffer;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.annotation.stuffer.MethodTypeEnum;
import com.sd365.common.core.common.advice.MyPageInfo;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.code.BizErrorCode;
import com.sd365.common.core.common.exception.code.CommonErrorCode;
import com.sd365.common.core.common.service.AbstractBusinessService;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.common.util.BeanException;
import com.sd365.common.util.BeanUtil;
import com.sd365.permission.centre.dao.mapper.PositionMapper;
import com.sd365.permission.centre.entity.Position;
import com.sd365.permission.centre.pojo.dto.CompanyDTO;
import com.sd365.permission.centre.pojo.dto.DeletePositionDTO;
import com.sd365.permission.centre.pojo.dto.OrganizationDTO;
import com.sd365.permission.centre.pojo.dto.PositionDTO;
import com.sd365.permission.centre.pojo.query.PositionQuery;
import com.sd365.permission.centre.service.PositionService;
import com.sd365.permission.centre.service.exception.UserCentreExceptionCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import tk.mybatis.mapper.entity.Example;

import javax.validation.Valid;
import java.util.List;

import static org.springframework.util.Assert.isTrue;
import static org.springframework.util.Assert.notEmpty;

@Service
public class PositionServiceImpl extends AbstractBusinessService implements PositionService {

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private IdGenerator idGenerator;


    @CommonFieldStuffer(methodType = MethodTypeEnum.ADD)
    @Override
    public Boolean add(@Valid PositionDTO postionDTO) {
        Position position= BeanUtil.copy(postionDTO, Position.class);
        position.setId(idGenerator.snowflakeId());
        super.baseDataStuff4Add(position);
        return positionMapper.insert(position)>0 ;
    }

    @Override
    public Boolean remove(Long id, Long version) {
        Example example=new Example(Position.class);
        example.createCriteria().andEqualTo("id",id).andEqualTo("version",version);
        return positionMapper.deleteByExample(example)>0;
    }


    @Override
    public Boolean modify(PositionDTO postionDTO) {
        try {
            Position position= BeanUtil.copy(postionDTO, Position.class);
            Example example=new Example(Position.class);
            example.createCriteria().andEqualTo("id",postionDTO.getId()).andEqualTo("version",postionDTO.getVersion());

            super.baseDataStuff4Updated(position);
            return positionMapper.updateByExampleSelective(position,example)>0 ;

        }catch (BeanException ex){
            throw new BusinessException(CommonErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        }
    }

    @Pagination
    @CommonFieldStuffer(methodType = MethodTypeEnum.QUERY)
    @Override
    public List<PositionDTO> commonQuery(PositionQuery postionQuery) {
        if(postionQuery==null){
            throw new BusinessException(BizErrorCode.PARAM_VALID_FIELD_REQUIRE,new Exception("commonQuery 参数不能为空"));
        }

            Position position=new Position();
            position.setId(postionQuery.getId());
            position.setName(postionQuery.getName());
            position.setCode(postionQuery.getCode());


            //将总数 页数都拷贝到ThreadLocal
            List<Position> positions=positionMapper.commonQuery(position);
            setPageInfo2BaseContextHolder((Page)positions);
            //对象转化 po list to dto list
            List<PositionDTO> positionDTOS= BeanUtil.copyList(positions, PositionDTO.class, new BeanUtil.CopyCallback() {
                @Override
                public void copy(Object o, Object o1) {
                    // 调用 BeanUtil.copyProperties
                    if(o==null || o1==null) {
                        throw new BeanException("拷贝对象不可以为空", new Exception("copyList 拷贝回调错误"));
                    }
                    Position positionSource=(Position)o;
                    PositionDTO positionDTO=(PositionDTO)o1;

                    BeanUtil.copy(positionSource.getCompany(),positionDTO.getCompanyDTO(), CompanyDTO.class);
                    BeanUtil.copy(positionSource.getOrganization(),positionDTO.getOrganizationDTO(), OrganizationDTO.class);
                }
            });

            return positionDTOS;

    }

    @Override
    public PositionDTO queryById(Long id) {
        try{
            PositionDTO positionDTO=null;
            Position position= positionMapper.selectPositionById(id);
            if(position!=null) {
                positionDTO = BeanUtil.copy(position, PositionDTO.class);

                BeanUtil.copy(position.getCompany(),positionDTO.getCompanyDTO(), CompanyDTO.class);
                BeanUtil.copy(position.getOrganization(),positionDTO.getOrganizationDTO(), OrganizationDTO.class);
            }
            return positionDTO;
        }catch (BeanException ex){
            throw new BusinessException(CommonErrorCode.SYSTEM_BEAN_COPY_EXCEPTION,ex);
        }
    }

    @CommonFieldStuffer(methodType = MethodTypeEnum.DELETE)
    @Override
    public Boolean batchDelete(DeletePositionDTO[] deletePositionDTOS) {
        notEmpty(deletePositionDTOS,"批量删除参数不可以为空");
        for(DeletePositionDTO deletePositionDTO : deletePositionDTOS){
            Example example=new Example(Position.class);
            example.createCriteria().andEqualTo("id",deletePositionDTO.getId()).andEqualTo("version",deletePositionDTO.getVersion()) ;
            int result=positionMapper.deleteByExample(example);
            isTrue(result>0,String.format("删除的记录id %d 没有匹配到版本",deletePositionDTO.getId()));
        }
        return true;
    }


    @Override
    public Boolean batchUpdate(PositionDTO[] positionDTOS) {
        Assert.noNullElements(positionDTOS,"更新数组不能为空");
        for(PositionDTO positionDTO:positionDTOS){
            Position position=BeanUtil.copy(positionDTO,Position.class);
            Example example=new Example(position.getClass());
            example.createCriteria().andEqualTo("id",position.getId()).andEqualTo("version",positionDTO.getVersion());;
            super.baseDataStuff4Updated(position);
            int result=positionMapper.updateByExampleSelective(position,example);
            Assert.isTrue(result>0,"没有找到相应id更新记录");
        }
        return true;
    }
}
